<template>
  <!-- 项目详情对话框 -->
  <el-dialog
      v-model="dialogVisible"
      title="项目详情"
      :close-on-click-modal="false"
      width="80%"
      class="fixed-footer-dialog"
  >
    <div class="dialog-box dialog-content-scroll">
      <!-- 项目信息部分 -->
      <div>
        <div class="dialog-one-title">
          <span>项目信息</span>
          <el-link
              type="primary"
              v-if="projectInfo.processInstanceId != null && projectInfo.processInstanceId != ''"
              class="title-right"
              @click="checkHistoryModalVisible = true"
          >
            审核记录
          </el-link>
        </div>
        <!-- 项目信息描述表格 -->
        <el-descriptions :column="2" border class="equal-width-descriptions">
          <el-descriptions-item label="项目名称" max-width="300">
            <!-- 显示项目名称 -->
            <span>{{ projectInfo.name }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="批准经费">
            <!-- 将批准经费转换为万元显示 -->
            {{ turnWanyuan(projectInfo.feeAuthorize) }}
          </el-descriptions-item>
          <el-descriptions-item label="负责人">{{ projectInfo.chargerName }}</el-descriptions-item>
          <el-descriptions-item label="所属单位">{{ projectInfo.unitName }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ projectInfo.beginDate }}</el-descriptions-item>
          <el-descriptions-item label="计划完成日期">{{ projectInfo.planEndDate }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <!-- 调账说明部分 -->
      <div>
        <div class="title-col">调账说明</div>
        <div>1、当前项目是按照入账经费分配经费卡额度。</div>
        <div>2、调账后需保证所有经费卡的入账总额不发生变化。</div>
        <div>3、调账后需保证所有经费卡的每个科目额度之和不超过科目总留校预算。</div>
        <div>4、调账后需保证每张卡的入账总金额等于经费卡入账总额度。</div>
        <div>5、科目额度增加时调整量填写正数，例如+0.2；额度减少时调整量填写负数，例如-0.2；当科目额度调整量为负数时，其绝对值不能大于科目额度结余。</div>
      </div>
      <!-- 经费卡入账记录部分 -->
      <div>
        <div class="title-col">经费卡入账记录(单位：万元)</div>
        <div>
          <!-- 经费卡基本信息描述表格 -->
          <el-descriptions :column="1" border class="equal-width-descriptions">
            <el-descriptions-item align="center" label="经费卡负责人">{{ projectInfo.feeChargerName }}</el-descriptions-item>
            <el-descriptions-item align="center" label="经费卡号">{{ projectInfo.feeCardNum }}</el-descriptions-item>
            <el-descriptions-item align="center" label="所属单位（经费卡）">{{ projectInfo.unitName }}</el-descriptions-item>
            <el-descriptions-item align="center" label="累计入账">
              <!-- 将累计入账金额转换为万元显示 -->
              {{ turnWanyuan(projectInfo.incomeTotal) }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="入账结余">
              <!-- 计算并将入账结余转换为万元显示 -->
              {{ turnWanyuan(parseFloat(projectInfo.feeAuthorize) - parseFloat(projectInfo.incomeTotal)) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div>
          <!-- 经费科目树形表格 -->
          <el-table
              :data="treeData"
              border
              row-key="subjectId"
              default-expand-all
              :tree-props="{ children: 'children' }"
          >
            <el-table-column prop="subjectName" label="科目名称"></el-table-column>
            <el-table-column prop="subjectFee" label="总预算">
              <template #default="scope">
                <!-- 将科目总预算转换为万元显示 -->
                {{ turnWanyuan(scope.row.subjectFee) }}
              </template>
            </el-table-column>
            <el-table-column prop="allincome" label="累计入账额度">
              <template #default="scope">
                <!-- 将科目累计入账额度转换为万元显示 -->
                {{ turnWanyuan(scope.row.allincome) }}
              </template>
            </el-table-column>
            <el-table-column prop="balance" label="额度结余">
              <template #default="scope">
                <!-- 将科目额度结余转换为万元显示 -->
                {{ turnWanyuan(scope.row.balance) }}
              </template>
            </el-table-column>
            <el-table-column prop="budgetFeeChange" label="调整量">
              <template #default="scope">
                <!-- 显示科目调整量（已转换为万元） -->
                <span>{{ turnWanyuan(scope.row.budgetFeeChange) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="afterAmount" label="调整后入账额度">
              <template #default="scope">
                <!-- 将科目调整后入账额度转换为万元显示 -->
                {{ turnWanyuan(scope.row.afterAmount) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 调账原因显示 -->

      <div class="cards-flex">
        <div class="cards">
          调账原因
        </div>
        <div class="cards-text">
          {{ projectInfo.alterreason }}
        </div>
<!--        <el-descriptions :column="1" border class="equal-width-descriptions">-->
<!--          <el-descriptions-item label="调账原因" >-->
<!--            <span>{{ projectInfo.alterreason }}</span>-->
<!--          </el-descriptions-item>-->
<!--        </el-descriptions>-->
      </div>
    </div>

    <template #footer>
      <div >
<!--        &lt;!&ndash; 暂存按钮 &ndash;&gt;-->
<!--        <el-button @click="handleSave">暂存</el-button>-->
<!--        &lt;!&ndash; 提交按钮 &ndash;&gt;-->
<!--        <el-button @click="submit">提交</el-button>-->
<!--        &lt;!&ndash; 保存并通过按钮 &ndash;&gt;-->
<!--        <el-button type="primary" @click="handleSaveAndPass">保存并通过</el-button>-->
        <!-- 关闭对话框按钮 -->
        <div v-if="showCheckcomponents">
          <Checkcomponents :procInsId="procInsId"  @success="success" class="mt-[10px]" />
        </div>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>


      </div>
    </template>

  </el-dialog>
  <CheckHistoryModal
      v-model="checkHistoryModalVisible"
      :procInsId="projectInfo.processInstanceId"
      :checker="projectInfo.checker"
      :checkDate="projectInfo.checkdate"
  />
</template>

<script setup lang="ts">
//查看审核流程
const  checkHistoryModalVisible = ref(false)
// checkdate: "2025-05-06 13:41:24"
// checker: "白雪

//审核
import Checkcomponents from "@/views/flowable/processInstance/detail/components.vue";

const emit = defineEmits(['success'])
const showCheckcomponents = ref(false)
import CheckHistoryModal from "@/views/project/components/CheckHistoryModal.vue";
const procInsId = ref('')
const success = function (){
  emit('success')
  dialogVisible.value = false
}
//审核
import { ref, watch } from "vue";
// 引入金额转换函数
import { turnWanyuan } from "../../../utils/money";
// 引入接口请求函数
import { selectVproject, getBudgetInfo, geteditInfo, edit } from "./../../../api/money/jfdzApi";
// 引入消息提示组件
import { ElMessage } from "element-plus";
// 引入对象合并工具函数
import { assign } from "lodash";

// 获取项目下拉选项
const getprojectOptions = (row) => {
  // 调用接口获取项目列表
  selectVproject({
    pageNum: 1,
    pageSize: 50,
    // name: row.projectName
    id:row.projectId
  }).then((res) => {
    // 找到当前选中的项目
    const selectedProject = res.rows.find(item => item.projectId === row.projectId);
    if (selectedProject) {
      // 更新项目信息
      projectInfo.value = {
        ...projectInfo.value,
        ...selectedProject
      };
    }
    // 处理项目信息变化
    changeprojectOptions(row);
  });
};

// 存储项目顶部信息
const DialogTop = ref({});
// 存储项目中间信息
const DialogMid = ref({});

// 初始化树形表格数据
const initData = (data, parent = null) => {
  data.forEach((item) => {
    // 记录父节点
    item.$parent = parent;
    // 提取并转换相关数据
    const { allincome, allpayout, budgetFeeChange } = item.alterationVals[0];
    item.allincome = Number(allincome);
    item.allpayout = allpayout!== null? Number(allpayout) : null;
    item.budgetFeeChange = budgetFeeChange? Number(budgetFeeChange) : 0;
    item.budgetFeeChangeInWan = item.budgetFeeChange / 10000;
    // 计算调整后入账额度
    item.afterAmount = item.allincome + item.budgetFeeChange;
    // 计算额度结余
    item.balance = item.subjectFee? Number(item.subjectFee) - item.allincome : 0;

    // 递归处理子节点
    if (item.children && item.children.length > 0) {
      initData(item.children, item);
      // 汇总子节点累计入账额度
      item.allincome = item.children.reduce((sum, child) => sum + child.allincome, 0);
      // 汇总子节点调整量
      item.budgetFeeChange = item.children.reduce((sum, child) => sum + child.budgetFeeChange, 0);
      item.budgetFeeChangeInWan = item.budgetFeeChange / 10000;
      // 汇总子节点调整后入账额度
      item.afterAmount = item.children.reduce((sum, child) => sum + child.afterAmount, 0);
      // 重新计算父节点额度结余
      item.balance = item.subjectFee? Number(item.subjectFee) - item.allincome : 0;
    }
  });
};

// 处理项目信息变化
const changeprojectOptions = (itemObj) => {
  console.log(itemObj)
  // 调用接口获取项目详细信息
  geteditInfo({
    Id: itemObj.id
  }).then((res) => {
    // 找到当前选中项目的顶部信息
    DialogTop.value = projectOptions.value.find((item) => item.id === projectInfo.value.projectId);
    // 存储项目中间信息
    DialogMid.value = res.data.amountAlterationVO[0];
    // 存储经费科目树形数据
    treeData.value = res.data.budgetAmountAlterationVO;
    projectInfo.value.alterreason = res.data.alterreason
    // 初始化树形数据
    initData(treeData.value);
    // 合并项目信息
    Object.assign(projectInfo.value, DialogTop.value, DialogMid.value,itemObj);
    //console.log(projectInfo.value)
  });
};

// 处理所有调整量*10000
function multiplyBudgetFeeChangeBy10000(treeData) {
  if (!Array.isArray(treeData)) {
    return treeData;
  }

  treeData.forEach((item) => {
    if (item.budgetFeeChange!== undefined) {
      item.budgetFeeChange = Number(item.budgetFeeChange);
    }

    if (item.children && item.children.length > 0) {
      multiplyBudgetFeeChangeBy10000(item.children);
    }
  });

  return treeData;
}

// 处理替换"alterationVals": [}里面 调整量 调整后入账额度
function replaceBudgetFeeChangeAndAfterAmountInAlterationVals(treeData) {
  if (!Array.isArray(treeData)) {
    return treeData;
  }

  treeData.forEach((item) => {
    if (item.alterationVals && Array.isArray(item.alterationVals)) {
      item.alterationVals.forEach((alteration) => {
        if (item.budgetFeeChange!== undefined) {
          alteration.budgetFeeChange = item.budgetFeeChange;
        }
        if (item.afterAmount!== undefined) {
          alteration.afterAmount = item.afterAmount;
        }
      });
    }

    if (item.children && Array.isArray(item.children)) {
      replaceBudgetFeeChangeAndAfterAmountInAlterationVals(item.children);
    }
  });

  return treeData;
}

function removeCircularReferences(obj, visited = new WeakSet()) {
  if (typeof obj!== "object" || obj === null) {
    return obj;
  }
  if (visited.has(obj)) {
    return;
  }
  visited.add(obj);
  const newObj = Array.isArray(obj)? [] : {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (key === "$parent") {
        // 跳过 $parent 属性以避免循环引用
        continue;
      }
      newObj[key] = removeCircularReferences(obj[key], visited);
    }
  }
  return newObj;
}

// 提交按钮点击事件处理函数
const submit = () => {
  // 检查是否填写调账原因
  if (projectInfo.value.alterreason === "") {
    ElMessage({
      message: "请填写调账说明",
      type: "error"
    });
    return;
  }

  let cleanTreeData = removeCircularReferences(treeData.value);
  let GoOut = {
    status: "1",
    ...projectInfo.value,
    amountAlterationVO: [projectInfo.value],
    budgetAmountAlterationVO: replaceBudgetFeeChangeAndAfterAmountInAlterationVals(
        multiplyBudgetFeeChangeBy10000(cleanTreeData)
    )
  };
  // afterAmount: 50000调整后入账
  // allincome: 50000 累计入账
  const incomeTotal = parseFloat(GoOut.incomeTotal);
  // if (GoOut.budgetAmountAlterationVO[0].allincome > GoOut.budgetAmountAlterationVO[0].afterAmount || GoOut.budgetAmountAlterationVO[0].afterAmount > incomeTotal) {
  //   ElMessage({
  //     message: '项目直接费用合计的累计入账额度应小于等于调整后入账额度，且调整后入账额度应小于等于累计入账',
  //     type: 'error'
  //   });
  //   return;
  // }
  // 调用接口提交数据
  edit(GoOut).then((res) => {
    if (res.code === 200) {
      ElMessage({
        message: res.msg,
        type: "success"
      });
      // 关闭对话框
      dialogVisible.value = false;
    } else {
      ElMessage({
        message: res.msg,
        type: "error"
      });
    }
  });
  console.log("projectInfo", GoOut);
  console.log("treeData", treeData.value);
};

// 保存按钮点击事件处理函数
const handleSave = () => {
  // 检查是否填写调账原因
  if (projectInfo.value.alterreason === "") {
    ElMessage({
      message: "请填写调账说明",
      type: "error"
    });
    return;
  }

  let cleanTreeData = removeCircularReferences(treeData.value);
  let GoOut = {
    status: "-1",
    ...projectInfo.value,
    amountAlterationVO: [projectInfo.value],
    budgetAmountAlterationVO: replaceBudgetFeeChangeAndAfterAmountInAlterationVals(
        multiplyBudgetFeeChangeBy10000(cleanTreeData)
    )
  };
  // afterAmount: 50000调整后入账
  // allincome: 50000 累计入账
  const incomeTotal = parseFloat(GoOut.incomeTotal);
  // if (GoOut.budgetAmountAlterationVO[0].allincome > GoOut.budgetAmountAlterationVO[0].afterAmount || GoOut.budgetAmountAlterationVO[0].afterAmount > incomeTotal) {
  //   ElMessage({
  //     message: '项目直接费用合计的累计入账额度应小于等于调整后入账额度，且调整后入账额度应小于等于累计入账',
  //     type: 'error'
  //   });
  //   return;
  // }
  // 调用接口保存数据
  edit(GoOut).then((res) => {
    if (res.code === 200) {
      ElMessage({
        message: res.msg,
        type: "success"
      });
      // 关闭对话框
      dialogVisible.value = false;
    } else {
      ElMessage({
        message: res.msg,
        type: "error"
      });
    }
  });
  console.log("projectInfo", GoOut);
  console.log("treeData", treeData.value);
};

// 保存并通过按钮点击事件处理函数
const handleSaveAndPass = () => {
  // 检查是否填写调账原因
  if (projectInfo.value.alterreason === "") {
    ElMessage({
      message: "请填写调账说明",
      type: "error"
    });
    return;
  }

  let cleanTreeData = removeCircularReferences(treeData.value);
  let GoOut = {
    status: "2",
    ...projectInfo.value,
    amountAlterationVO: [projectInfo.value],
    budgetAmountAlterationVO: replaceBudgetFeeChangeAndAfterAmountInAlterationVals(
        multiplyBudgetFeeChangeBy10000(cleanTreeData)
    )
  };
  // afterAmount: 50000调整后入账
  // allincome: 50000 累计入账
  const incomeTotal = parseFloat(GoOut.incomeTotal);
  // if (GoOut.budgetAmountAlterationVO[0].allincome > GoOut.budgetAmountAlterationVO[0].afterAmount || GoOut.budgetAmountAlterationVO[0].afterAmount > incomeTotal) {
  //   ElMessage({
  //     message: '项目直接费用合计的累计入账额度应小于等于调整后入账额度，且调整后入账额度应小于等于累计入账',
  //     type: 'error'
  //   });
  //   return;
  // }
  // 调用接口保存并通过数据
  edit(GoOut).then((res) => {
    if (res.code === 200) {
      ElMessage({
        message: res.msg,
        type: "success"
      });
      // 关闭对话框
      dialogVisible.value = false;
    } else {
      ElMessage({
        message: res.msg,
        type: "error"
      });
    }
  });
  console.log("保存并通过操作");
  dialogVisible.value = false;
};

// 模拟树形表格数据
const treeData = ref([
  // 数据内容省略，保持不变
]);
// 项目名称下拉框选项
const projectOptions = ref([]);
// 项目信息
const projectInfo = ref({
  projectId: "",
  projectName: "",
  feeAuthorize: "",
  chargerName: "",
  unitName: "",
  beginDate: "",
  planEndDate: "",
  feeChargerName: "",
  feeCardNum: "",
  incomeTotal: "",
  entryBalance: "",
  adjustmentFee: "0",
  afterFee: "",
  alterreason: "",
  processInstanceId:'',
});
// 控制对话框显示与隐藏
const dialogVisible = ref(false);

// 打开对话框
const opencompileDialog = (row ,name) => {
  console.log(row)
  console.log(name)
  dialogVisible.value = true;
  projectInfo.value.projectId = row.projectId;
  // 获取项目下拉选项
  getprojectOptions(row);
  if (row.hasOwnProperty('isAuditor') && row.isAuditor === true) {
    if (row.checkstatus == 1 && name != 'name') {
      showCheckcomponents.value = false
      if (row.processInstanceId == null) {
        ElMessage({
          message: 'processInstanceId为空',
          type: "error"
        });
        return
      }
      showCheckcomponents.value = true
      console.log(row)
      procInsId.value = row.processInstanceId

    }else if(row.checkstatus == null && name == 'shenhename'){
      showCheckcomponents.value = false
      if (row.processInstanceId == null) {
        ElMessage({
          message: 'processInstanceId为空',
          type: "error"
        });
        return
      }
      showCheckcomponents.value = true
      console.log(row)
      procInsId.value = row.processInstanceId

    }else if(row.checkstatus == 1 && name == 'name'){
      showCheckcomponents.value = false
      if (row.processInstanceId == null) {
        ElMessage({
          message: 'processInstanceId为空',
          type: "error"
        });
        return
      }
      showCheckcomponents.value = true
      console.log(row)
      procInsId.value = row.processInstanceId
    }
  }else {
    showCheckcomponents.value = false
    if (row.processInstanceId == null) {
      ElMessage({
        message: 'processInstanceId为空',
        type: "error"
      });
      return
    }
    console.log(row)
    procInsId.value = row.processInstanceId
  }


}

// 暴露打开对话框方法供父组件调用
defineExpose({
  opencompileDialog
});
</script>

<style scoped lang="scss">
.dialog-one-title {
  height: 30px;
  width: 100%;
  font-size: 16px;
  font-weight: bolder;
  border-bottom: 2px solid #ffce55;
}

.dialog-box > div {
  margin: 10px 0;
}

.title-col {
  color: #337AB7;
  font-weight: bolder;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.equal-width-descriptions.el-descriptions__item {
  width: calc(100% / var(--el-descriptions-column));
}
/* 设置标题宽度 */
:deep(.equal-width-descriptions.el-descriptions__label) {
  width: 200px; /* 可以根据需要调整宽度值 */
}
.title-right{
 margin-left: 89%;
}
.cards-flex{
  display: flex;
  border: 1px solid #e5e7eb ;

}
.cards{
  display: flex;
  align-items: center;
  /* 可以根据需要添加其他样式 */
  padding: 10px;
  background-color: #f5f7fa;
  text-align: center;
  font-weight: bolder;
  min-width: 150px;
}
.cards-text{
 padding: 8px;
}
.bottom{
  position: absolute;
  top: 550px;
  width: 98%;
  z-index: 99;
  background-color: #da1a1a;
}
/* 固定高度和滚动条样式 */
.fixed-footer-dialog {
  .el-dialog__body {
    max-height: 40vh; // 设置最大高度为视口高度的60%
    overflow-y: auto; // 添加垂直滚动条
    padding-bottom: 80px; // 为固定底部留出空间
  }

  .el-dialog__footer {
    position: absolute; // 使用绝对定位而非固定定位
    bottom: 0;
    left: 0;
    right: 0;
    background-color: white;
    border-top: 1px solid #ebeef5;
    padding: 15px 20px;
    z-index: 10; // 确保在内容之上
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  }
}

/* 优化表格区域的滚动体验 */
.dialog-content-scroll {
    max-height: 60vh; // 限制表格最大高度
    overflow: auto;
    display: block; // 确保表格正确处理高度

}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>